import React, { useState, useMemo, useEffect, useRef } from 'react'
import { Table, Button, Tag, message, Modal, Result, Space } from 'antd'
import {
  CheckCircleOutlined,
  MailOutlined,
  VerticalAlignBottomOutlined,
  CloseCircleOutlined
} from '@ant-design/icons'
import Filter from './Filter'
import sourceImg from '&/assets/images/imgs'
import Container from '@/appComponents/Container'
import ConText from './ConText'
import ModerFeed from './ModerFeed'
import { dataURLtoFile, FiletoDataURL } from '&/utils/file.help'
import {
  getClueList,
  postWarnClueAssign,
  postWarnClueClose,
  getClueDelete //线索删除
} from '&/api/electricity'
import TagCompent from '@/appComponents/TagCompent'
import SpanNum from '@/appComponents/SpanNum'
import './index.scss'
import dayjs from 'dayjs'
const { confirm } = Modal
const MatterList = () => {
  const value = JSON.parse(localStorage.getItem('user'))
  const [checkStrictly, setCheckStrictly] = useState(false)
  const [listArr, setListArr] = useState([])
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [feedVisible, setFeedVisible] = useState(false) //反馈弹窗
  const [feedRecord, setFeedRecord] = useState() //点击已反馈所拿到的数据
  const [total, setTotal] = useState()
  const [paramsData, setParamsData] = useState({
    start_time: dayjs().subtract(1, 'd').format('YYYY-MM-DD 00:00:00'),
    end_time: dayjs().format('YYYY-MM-DD 23:59:59'),
    adm_id: value?.adm_id,
    ent_name: '',
    userid: value?.userid,
    role_level: value?.role_level,
    assign_status: '-1',
    feedback_status: '-1',
    page: 1,
    page_size: 10
  })

  const json = useMemo(() => {
    let newParamsData = {}
    for (let key in paramsData) {
      if (paramsData[key] != (-1 || '-1')) {
        newParamsData[key] = paramsData[key]
      }
    }
    return newParamsData
  }, [paramsData.assign_status, paramsData.feedback_status])
  useEffect(() => {
    onQuery(json)
  }, [json])

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys)
      const arr = selectedRows.map((item) => {
        return item.clue_code
      })
      setListArr(arr)
    }
  }
  const onQuery = async (value) => {
    value.page = 1
    getClueListRequest(value)
  }
  const getClueListRequest = async (value) => {
    value.type = 1
    // console.log(value);
    setLoading(true)
    const res = await getClueList(value)
    setTotal(res.page_info.total_number)
    // setData(res.data)
    setParamsData((state) => {
      state.page = res.page_info.page
      state.page_size = res.page_info.page_size
      return {
        ...state
      }
    })
    setData([])  //暂时没有列表接口，所以先搭建一个页面，把数据设为空

    setLoading(false)
  }
  const handClickDelet = async (values) => {
    const formdata = new FormData()
    formdata.append('userid', value?.userid)
    formdata.append('clue_code', JSON.stringify([values?.clue_code]))
    const res = await getClueDelete(formdata)
    message.success(res?.data.result)
    onQuery(json)

  }
  //批量关闭 
  const handClickAllClose = () => {

  }
  //批量下发
  const handClickAllXiaFa = () => {

  }
  //单个点击下发
  const handClickXiaFa = (value) => {

  }
  const columns = [
    {
      title: '序号',
      width: 50,
      render: (text, item, index) => {
        return index + 1
      },
      align: 'center'
    },
    {
      title: '企业名称',
      dataIndex: 'ent_name',
      key: 'ent_name',
      align: 'center',
      width: 150
    },
    {
      width: 100,
      title: '编号',
      dataIndex: 'clue_code',
      key: 'clue_code',
      align: 'center',
      render: (_, record) => {
        return (
          <div style={{ textAlign: 'center' }}>
            <div>{_}</div>
          </div>
        )
      }
    },
    {
      title: '问题描述',
      dataIndex: 'desc',
      key: 'desc',
      align: 'center',
      width: 700,
      render: (text) => {
        if (text) {
          return (
            <div
              style={{
                // overflowY: 'auto',
                // maxHeight: '240px',
                display: 'flex',
                justifyContent: 'left',
                alignItems: 'center'
              }}
            >
              <ConText data={text}></ConText>
            </div>
          )
        }
      }
    },
    {
      title: '下发状态',
      dataIndex: 'assign_status',
      key: 'assign_status',
      align: 'center',
      width: 80,
      render: (text) => {
        const color = text == 0 ? 'green' : 'green'
        return <Tag color={color}>{text == 0 ? '已下发' : '已下发'}</Tag>
      }
    },
    {
      title: '反馈状态',
      dataIndex: 'feedback_status',
      key: 'feedback_status',
      align: 'center',
      width: 120,
      render: (text, record) => {
        const color = text == 0 ? 'red' : 'green'
        return (
          <>
            <Tag color={color}>{text == 0 ? '未反馈' : '已反馈'}</Tag>
            {/* <MailOutlined /> */}
            {text !== 0 ? (
              <Button
                // disabled={true}
                size="small"
                type="primary"
                shape="circle"
                icon={<MailOutlined />}
                onClick={() => {
                  setFeedVisible(true)
                  setFeedRecord(record)
                }}
              ></Button>
            ) : null}
          </>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'caozuo',
      key: 'caozuo',
      align: 'center',
      width: 180,
      //  fixed: 'right',
      render: (_, record) => {
        // console.log(record,"record--");
        return (
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={() => handClickXiaFa(record)}
              icon={<VerticalAlignBottomOutlined />}
              disabled={
                record.is_closed == 0 && record.assign_status == 0
                  ? false
                  : true
              }
            >
              下发
            </Button>
            <Button
              type="primary"
              size="small"
              onClick={() => handClickDelet(record)}
            // disabled={record.is_closed == 0 ? false : true}
            >
              删除
            </Button>
          </Space>
        )
      }
    }
  ]
  return (
    <div className="MatterList">
      <Container>
        <Container.ContainerQuery title="查询条件">
          <div className="MatterList-top">
            <div>
              <Filter
                onQuery={onQuery}
                paramsData={paramsData}
                setParamsData={setParamsData}
              />
            </div>
          </div>
        </Container.ContainerQuery>
        <Container.ContainerContent
          title="查询结果"
          extra={
            <div>
              <Button
                style={{
                  marginRight: 10
                }}
                type="primary"
                onClick={handClickAllXiaFa}
                disabled={selectedRowKeys.length > 0 ? false : true}
                icon={<VerticalAlignBottomOutlined />}
              >
                批量下发
              </Button>

              <Button
                type="primary"
                danger
                disabled={selectedRowKeys.length > 0 ? false : true}
                onClick={handClickAllClose}
                icon={<CloseCircleOutlined />}
              >
                批量关闭
              </Button>
            </div>
          }
        >
          <Table
            bordered
            tableLayout="fixed"
            loading={loading}
            columns={columns}
            dataSource={data}
            size="small"
            rowSelection={{
              ...rowSelection,
              checkStrictly
            }}
            rowKey={(row) => {
              return JSON.stringify(row)
            }}
            pagination={{
              showTotal: (total) => `总共 ${total} 条线索`,
              current: paramsData.page,
              pageSize: paramsData.page_size,
              position: ['bottomCenter'],
              showSizeChanger: true,
              total: total && total,
              onChange: (page, pageSize) => {
                let newParamsData = {}
                for (let key in paramsData) {
                  if (paramsData[key] != (-1 || '-1')) {
                    newParamsData[key] = paramsData[key]
                  }
                }
                newParamsData.page = page
                newParamsData.page_size = pageSize
                // console.log(newParamsData, "newParamsData======");
                getClueListRequest(newParamsData)
              }
            }}
            scroll={{
              y: '62vh'
            }}
          />
          <ModerFeed
            visible={feedVisible}
            setVisible={setFeedVisible}
            records={feedRecord}
          ></ModerFeed>
        </Container.ContainerContent>
      </Container>
    </div>
  )
}
export default MatterList
